package com.tina.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tina.entity.TiRole;
import com.tina.entity.TiRoleMenuRef;
import com.tina.entity.TiUsersRoleRef;
import com.tina.entity.vo.TiMenuVo;
import com.tina.mapper.TiRoleMapper;
import com.tina.mapper.TiRoleMenuRefMapper;
import com.tina.mapper.TiUsersRoleRefMapper;
import com.tina.service.TiRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tina.util.RedisUtil;
import com.tina.util.TimeUtitl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author PIGS
 * @since 2020-06-05
 */
@Service
@Transactional
public class TiRoleServiceImpl extends ServiceImpl<TiRoleMapper, TiRole> implements TiRoleService {
    private Logger logger = LoggerFactory.getLogger(TiRoleServiceImpl.class);

    @Autowired
    private TiUsersRoleRefMapper tiUsersRoleRefMapper;

    @Autowired
    private TiRoleMenuRefMapper tiRoleMenuRefMapper;

    @Autowired
    private TiRoleMapper tiRoleMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 查询用户 角色
     *
     * @param userId
     * @return
     */
    @Override
    public TiUsersRoleRef queryUserRoleInfo(Integer userId) {

        /**
         * redis中数据不存在就进入mysql中查询
         */
        if (userId != null) {
            AbstractWrapper wrapper = new QueryWrapper();
            wrapper.eq("users_id", userId);
            TiUsersRoleRef selectById = tiUsersRoleRefMapper.selectOne(wrapper);
            if (selectById != null) {
                redisUtil.set("tiUsersRoleRef:" + selectById.getUsersId(), selectById);
                logger.info("selectById={}", selectById);
                return selectById;
            }
        }

        return null;
    }

    /**
     * 条件查询角色信息 并分页
     *
     * @param tiRole
     * @param page
     * @param limit
     * @return
     */
    @Override
    public IPage<TiRole> queryRoleList(TiRole tiRole, Integer page, Integer limit) {
        AbstractWrapper<TiRole, String, QueryWrapper<TiRole>> wrapper = new QueryWrapper<TiRole>();

        if (tiRole != null) {
            if (!StringUtils.isEmpty(tiRole.getRoleName())) {
                wrapper.like("role_name", tiRole.getRoleName());
            }
        }

        wrapper.eq("role_state", tiRole.getRoleState());
        wrapper.orderByDesc("role_create_time");
        Page<TiRole> iPage = new Page<TiRole>(page, limit);
        Page<TiRole> tiRolePage = tiRoleMapper.selectPage(iPage, wrapper);
        return tiRolePage;
    }

    /**
     * 添加角色实现类
     *
     * @param tiRole
     * @return
     */
    @Override
    public Integer saveRole(TiRole tiRole, String select) {

        AbstractWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("role_name", tiRole.getRoleName());
        TiRole selectOne = tiRoleMapper.selectOne(wrapper);

        if (selectOne != null) {
            if (selectOne.getRoleName().equals(tiRole.getRoleName())) {
                return 101;
            }
        }

        AbstractWrapper wrapperDescription = new QueryWrapper<>();
        wrapperDescription.eq("role_description", tiRole.getRoleDescription());
        TiRole selectOneDescription = tiRoleMapper.selectOne(wrapperDescription);
        if (selectOneDescription != null) {
            if (selectOneDescription.getRoleDescription().equals(tiRole.getRoleDescription())) {
                return 102;
            }
        }

        tiRole.setRoleCreateTime(TimeUtitl.dateTime());
        Integer insertRole = tiRoleMapper.insert(tiRole);

        if (!StringUtils.isEmpty(select)) {
            String[] menuId;
            menuId = select.split(",");
            TiRoleMenuRef tiRoleMenuRef = new TiRoleMenuRef();
            for (String x : menuId) {
                tiRoleMenuRef.setMenuId(Long.valueOf(x));
                tiRoleMenuRef.setRoleId(Long.valueOf(tiRole.getRoleId()));
                tiRoleMenuRefMapper.insert(tiRoleMenuRef);
            }
        }

        if (insertRole > 0) {
            return 1;
        }
        return null;
    }

    /**
     * 条件查询角色信息
     *
     * @param tiRole
     * @return
     */
    @Override
    public TiRole queryRoleInfo(TiRole tiRole) {
        if (tiRole != null) {
            if (tiRole.getRoleId() != null) {
                AbstractWrapper wrapper = new QueryWrapper<>();
                wrapper.eq("role_id", tiRole.getRoleId());
                TiRole selectOne = tiRoleMapper.selectOne(wrapper);
                logger.info("queryRoleInfo={}", selectOne);
                if (selectOne != null) {
                    return selectOne;
                }
            }
        }
        return null;
    }

    /**
     * 修改角色信息
     * 返回 101说明角色名称已经存在
     * 返回 102说明角色标识已经存在
     *
     * @param tiRole
     * @return
     */
    @Override
    public Integer editRole(TiRole tiRole, String select) {

        TiRole selectById = tiRoleMapper.selectById(tiRole.getRoleId());
        AbstractWrapper wrapper = new QueryWrapper<TiRole>();
        wrapper.eq("role_name", tiRole.getRoleName());
        TiRole selectOne = tiRoleMapper.selectOne(wrapper);
        if (selectById != null) {
            if (selectOne != null) {
                if (!selectById.getRoleName().equals(tiRole.getRoleName())) {
                    return 101;
                }
            }
        }

        AbstractWrapper wrapperDescription = new QueryWrapper<>();
        wrapperDescription.eq("role_description", tiRole.getRoleDescription());
        TiRole selectOneDescription = tiRoleMapper.selectOne(wrapperDescription);
        if (selectById != null) {
            if (selectOneDescription != null) {
                if (!selectById.getRoleDescription().equals(tiRole.getRoleDescription())) {
                    return 102;
                }
            }
        }

        /**
         * 删除角色菜单权限
         * 然后保存新的菜单权限
         */
        Integer deleteRoleMenuByRoleId = tiRoleMenuRefMapper.deleteRoleMenuByRoleId(Long.valueOf(tiRole.getRoleId()));
        logger.info("deleteRoleMenuByRoleId={}", deleteRoleMenuByRoleId);

        if (!StringUtils.isEmpty(select)) {
            String[] menuId;
            menuId = select.split(",");
            TiRoleMenuRef tiRoleMenuRef = new TiRoleMenuRef();
            for (String x : menuId) {
                tiRoleMenuRef.setMenuId(Long.valueOf(x));
                tiRoleMenuRef.setRoleId(Long.valueOf(tiRole.getRoleId()));
                tiRoleMenuRefMapper.insert(tiRoleMenuRef);
            }
        }

        Integer updateByIdRole = tiRoleMapper.updateById(tiRole);
        logger.info("updateByIdRole={}", updateByIdRole);
        return updateByIdRole;
    }

    /**
     * 通过角色id查询菜单权限
     *
     * @param roleId
     * @return
     */
    @Override
    public List<TiMenuVo> queryRoleMenuRefListByRoleId(Long roleId) {
        if (roleId != null) {
            List<TiMenuVo> tiRoleMenuRefList = tiRoleMenuRefMapper.queryRoleMenuRefListByRoleId(roleId);
            return tiRoleMenuRefList;
        }
        return null;
    }
}
